package com.restkeeper.shop.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.shop.config.RabbitMQConfig;
import com.restkeeper.shop.entity.Store;
import com.restkeeper.shop.entity.StoreManager;
import com.restkeeper.shop.mapper.StoreManagerMapper;
import com.restkeeper.sms.SmsObject;
import com.restkeeper.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 门店管理员信息 服务实现类
 * </p>
 */
@Slf4j
@Service(version = "1.0.0",protocol = "dubbo")
public class StoreManagerServiceImpl extends ServiceImpl<StoreManagerMapper, StoreManager> implements IStoreManagerService {


    @Autowired @Qualifier("storeService")
    private IStoreService storeService;

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    //秘钥
    @Value("${gateway.secret}")
    private String secret;

    @Value("${sms.operator.signName}")
    private String signName;

    @Value("${sms.operator.templateCode}")
    private String templateCode;


    @Override
    public IPage page(String criteria, long page, long pageSize) {
        IPage<StoreManager> pageview = new Page<StoreManager>(page, pageSize);
        QueryWrapper<StoreManager> queryWrapper = new QueryWrapper<StoreManager>();
        if (!StringUtils.isEmpty(criteria)) {
            queryWrapper.lambda().eq(StoreManager::getStoreManagerName,criteria).or().
                    eq(StoreManager::getStoreManagerPhone,criteria);
        }
       return this.page(pageview,queryWrapper);
    }

    @Override
    public Result login(String shopId, String phone, String loginpass) {
        Result result = new Result();
        if (StringUtils.isEmpty(shopId)) {
            result.setStatus(ResultCode.error);
            result.setDesc("用户名为空");
            return result;
        }
        if (StringUtils.isEmpty(loginpass)) {
            result.setStatus(ResultCode.error);
            result.setDesc("密码为空");
            return result;
        }
        QueryWrapper<StoreManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StoreManager::getStoreManagerPhone,phone).eq(StoreManager::getShopId,shopId)
                .orderByDesc(StoreManager::getLastUpdateTime);
        //设置shop 参数
        RpcContext.getContext().setAttachment("shopId",shopId);
        StoreManager storeManager = this.getOne(queryWrapper);
        if (storeManager == null) {
            result.setStatus(ResultCode.error);
            result.setDesc("账号不存在");
            return result;
        }
        String salt = MD5CryptUtil.getSalts(storeManager.getPassword());
        if (!Md5Crypt.md5Crypt(loginpass.getBytes(), salt).equals(storeManager.getPassword())) {
            result.setStatus(ResultCode.error);
            result.setDesc("密码不正确");
            return result;
        }
        Map<String,Object> tokenMap = new HashMap<>();
        List<Store>  stores= storeManager.getStores();
        if(stores==null||stores.isEmpty()){
            result.setStatus(ResultCode.error);
            result.setDesc("没有门店");
            return result;
        }
        Store store = stores.get(0);
        tokenMap.put("shopId",shopId);
        tokenMap.put("storeId", store.getStoreId());
        tokenMap.put("loginUserId", storeManager.getStoreManagerId());
        tokenMap.put("loginUserName", storeManager.getStoreManagerName());
        tokenMap.put("userType",SystemCode.USER_TYPE_STORE_MANAGER); //门店管理员用户
        String authorization = "";
        try {
            authorization = JWTUtil.createJWTByObj(tokenMap, secret);
        } catch (IOException e) {
            log.error("加密失败", e.getMessage());
            result.setStatus(ResultCode.error);
            result.setDesc("加密失败");
            return result;
        }
        result.setStatus(ResultCode.success);
        result.setDesc("ok");
        result.setData(storeManager);
        result.setAuthorization(authorization);
        return result;
    }

    @Override
    public Result switchStore(String storeId) {
        Result result = new Result();
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("shopId", RpcContext.getContext().getAttachment("shopId"));
        tokenMap.put("storeId",storeId);
        tokenMap.put("loginUserId", RpcContext.getContext().getAttachment("loginUserId"));
        tokenMap.put("loginUserName", RpcContext.getContext().getAttachment("loginUserName"));
        tokenMap.put("userType",SystemCode.USER_TYPE_STORE_MANAGER); //门店管理员用户
        String authorization = "";
        try {
            authorization = JWTUtil.createJWTByObj(tokenMap, secret);
        } catch (IOException e) {
            log.error("加密失败", e.getMessage());
            result.setStatus(ResultCode.error);
            result.setDesc("加密失败");
            return result;
        }
        result.setStatus(ResultCode.success);
        result.setDesc("ok");
        result.setData(storeId);
        result.setAuthorization(authorization);
        return result;
    }

    @Override
    @Transactional
    public boolean addStoreManager(String name, String phone, List<String> storeIds) {
        boolean flag = true;
        try {
            StoreManager manager = new StoreManager();
            manager.setStoreManagerName(name);
            manager.setStoreManagerPhone(phone);
            String pwd =PassWordUtils.getRandom(8);
            manager.setPassword(Md5Crypt.md5Crypt(pwd.getBytes()));
            this.save(manager);
            String storeManagerId = manager.getStoreManagerId();
            UpdateWrapper<Store> updateWrapper = new UpdateWrapper<Store>();
            updateWrapper.lambda().in(Store::getStoreId, storeIds).set(Store::getStoreManagerId,storeManagerId);
             storeService.update(updateWrapper);
            //添加完成发送短信通知
            String shopId=RpcContext.getContext().getAttachment("shopId");
            sendMessage(phone,shopId,pwd);
        }catch (Exception ex){
            flag = false;
            log.info("新加管理员失败 {}",ex);
        }
        return flag;
    }



    private void sendMessage(String phone, String shopId, String pwd) {
        SmsObject smsObject = new SmsObject();
        smsObject.setPhoneNumber(phone);
        smsObject.setSignName(signName);
        smsObject.setTemplateCode(templateCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shopId", shopId);
        jsonObject.put("password", pwd);
        smsObject.setTemplateJsonParam(jsonObject.toJSONString());
        rabbitmqTemplate.convertAndSend(RabbitMQConfig.ACCOUNT_QUEUE, smsObject);
    }


    @Override
    @Transactional
    public boolean updateStoreManager(String storeManagerId, String name, String phone, List<String> storeIds) {
        boolean flag = true;
        try{
            StoreManager storeManager = this.getById(storeManagerId);
            if(!StringUtils.isEmpty(name)) {
                storeManager.setStoreManagerName(name);
            }
            //手机号修改后需要发送短信通知
            boolean sendMsg = false;
            if(!StringUtils.isEmpty(phone)) {
                sendMsg =true;
                storeManager.setStoreManagerPhone(phone);
            }
            this.updateById(storeManager);
            //去掉原有关系
            UpdateWrapper<Store> updateWrapper_pre = new UpdateWrapper<Store>();
            updateWrapper_pre.lambda().set(Store::getStoreManagerId,null).eq(Store::getStoreManagerId,storeManagerId);
            storeService.update(updateWrapper_pre);
            //建立新的关系
            UpdateWrapper<Store> updateWrapper_new = new UpdateWrapper<Store>();
            updateWrapper_new.lambda().in(Store::getStoreId, storeIds).set(Store::getStoreManagerId,storeManagerId);
            storeService.update(updateWrapper_new);
            if(sendMsg){
                //sendMessage(phone,shopId,);
            }
        }catch (Exception ex){
            log.error("修改异常 {}",ex);
            flag =false;
        }
        return  flag;
    }

    @Override
    @Transactional
    public boolean deleteStoreManager(String storeManagerId) {
        //逻辑删除
        this.removeById(storeManagerId);
        //去掉原有关系
        UpdateWrapper<Store> updateWrapper= new UpdateWrapper<Store>();
        updateWrapper.lambda().set(Store::getStoreManagerId,null).eq(Store::getStoreManagerId,storeManagerId);
        return  storeService.update(updateWrapper);
    }

    @Override
    public boolean updateStatus(String storeManagerId, int status) {
        UpdateWrapper<StoreManager> updateWrapper= new UpdateWrapper<>();
        updateWrapper.lambda().set(StoreManager::getStatus,status).eq(StoreManager::getStoreManagerId,storeManagerId);
        return this.update(updateWrapper);
    }
}
